import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wu_you/data/repository/auth_repository.dart';
import 'package:wu_you/l10n/messages.dart';
import 'package:wu_you/res/colors.dart';
import 'package:wu_you/utils/error_handler.dart';
import 'package:wu_you/utils/utils.dart';
import 'package:wu_you/widgets/countdown_view.dart';
import 'package:wu_you/utils/extension_utils.dart';

///注册
class RegPage extends StatefulWidget{
  @override
  RegPageState createState() => RegPageState();
}
class RegPageState extends State<RegPage>{
  final _countdownKey = GlobalKey<CountdownViewState>();
  final _formKey = GlobalKey<FormState>();
  TapGestureRecognizer _userProtocolRecognizer = TapGestureRecognizer();
  TapGestureRecognizer _privacyProtocolRecognizer = TapGestureRecognizer();
  String _account;
  String _mobile;
  String _pwd1;
  String _pwd2;
  String _smsCode;
  String _inviteCode;

  bool showPwd1 = false;
  bool showPwd2 = false;
  bool _isAgree = false;

  @override
  void initState() {
    super.initState();

    _userProtocolRecognizer.onTap = () {

    };
    _privacyProtocolRecognizer.onTap = () {


    };
  }

  var message;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text("${message['register']}"),
      ),
      body: SingleChildScrollView(
        child: Padding(
            padding: EdgeInsets.only(left: 25,right: 25,top: 20,bottom: 20),
            child: Form(
              key: _formKey,
              child: Column(
                children: [
                  TextFormField(
                    style: TextStyle(fontSize: 15,color: AppColors.textColor),
                    maxLines: 1,
                    textAlignVertical: TextAlignVertical.center,
                    textInputAction: TextInputAction.next,
                    keyboardType: TextInputType.text,
                    autofocus: false,
                    cursorColor: Theme.of(context).primaryColor,
                    validator: (value) {
                      return value.length == 0 ? '${message['enterAccount']}' : null;
                    },
                    onChanged: (value){
                      _account = value;
                    },
                    onSaved: (value) {
                      _account = value;
                    },
                    textAlign: TextAlign.start,
                    decoration: InputDecoration(
                      suffixIcon: IconButton(
                        splashColor: Colors.transparent,
                        highlightColor: Colors.transparent,
                        constraints: BoxConstraints.loose(Size(24, 24)),
                        iconSize: 1,
                        icon: Icon(Icons.clear,color: Colors.white,),
                        onPressed: () {
                        },
                      ),
                      border: UnderlineInputBorder(
                        borderSide: BorderSide.none,
                      ),
                      errorMaxLines: 1,
                      counterText: '',
                      contentPadding: EdgeInsets.only(left: 10),
                      hintText: "${message['enterAccount']}",
                      hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
                    ),
                  ),
                  Divider(
                    height: 2,
                    color: HexColor("#EAEAEA"),
                  ),
                  TextFormField(
                    style: TextStyle(fontSize: 15,color: AppColors.textColor),
                    maxLines: 1,
                    textAlignVertical: TextAlignVertical.center,
                    textInputAction: TextInputAction.done,
                    maxLength: 16,
                    keyboardType: TextInputType.text,
                    autofocus: false,
                    obscureText: showPwd1 ? false : true,
                    cursorColor: Theme.of(context).primaryColor,
                    validator: (value) {
                      return value.length == 0 ? '${message['enterPwd']}' : null;
                    },
                    onSaved: (value){
                      _pwd1 = value;
                    },
                    textAlign: TextAlign.start,
                    decoration: InputDecoration(
                      fillColor: Colors.white,
                      filled: true,
                      border: UnderlineInputBorder(
                        borderSide: BorderSide.none,
                        // borderRadius: const BorderRadius.all(Radius.circular(24)),
                      ),
                      suffixIcon: IconButton(
                        splashColor: Colors.transparent,
                        highlightColor: Colors.transparent,
                        constraints: BoxConstraints.loose(Size(24, 24)),
                        iconSize: 18,
                        icon: Image.asset(showPwd1 ? Utils.getImgPath('ic_password_yes') : Utils.getImgPath('ic_password_no'),width: 18,height: 18,),
                        onPressed: () {
                          showPwd1 = !showPwd1;
                          setState(() {});
                        },
                      ),
                      prefixIconConstraints: BoxConstraints.loose(Size(64, 50)),
                      errorMaxLines: 1,
                      counterText: '',
                      contentPadding: EdgeInsets.only(left: 10),
                      hintText: "${message['enterPwd']}",
                      hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
                    ),
                  ),
                  Divider(
                    height: 2,
                    color: HexColor("#EAEAEA"),
                  ),
                  TextFormField(
                    style: TextStyle(fontSize: 15,color: AppColors.textColor),
                    maxLines: 1,
                    textAlignVertical: TextAlignVertical.center,
                    textInputAction: TextInputAction.done,
                    maxLength: 16,
                    keyboardType: TextInputType.text,
                    autofocus: false,
                    obscureText: showPwd2 ? false : true,
                    cursorColor: Theme.of(context).primaryColor,
                    validator: (value) {
                      return value.length == 0 ? '${message['enterPwd']}' : null;
                    },
                    onSaved: (value){
                      _pwd2 = value;
                    },
                    textAlign: TextAlign.start,
                    decoration: InputDecoration(
                      fillColor: Colors.white,
                      filled: true,
                      border: UnderlineInputBorder(
                        borderSide: BorderSide.none,
                        // borderRadius: const BorderRadius.all(Radius.circular(24)),
                      ),
                      suffixIcon: IconButton(
                        splashColor: Colors.transparent,
                        highlightColor: Colors.transparent,
                        constraints: BoxConstraints.loose(Size(24, 24)),
                        iconSize: 18,
                        icon: Image.asset(showPwd2 ? Utils.getImgPath('ic_password_yes') : Utils.getImgPath('ic_password_no'),width: 18,height: 18,),
                        onPressed: () {
                          showPwd2 = !showPwd2;
                          setState(() {});
                        },
                      ),
                      prefixIconConstraints: BoxConstraints.loose(Size(64, 50)),
                      errorMaxLines: 1,
                      counterText: '',
                      contentPadding: EdgeInsets.only(left: 10),
                      hintText: "${message['enterPwdAgain']}",
                      hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
                    ),
                  ),
                  Divider(
                    height: 2,
                    color: HexColor("#EAEAEA"),
                  ),
                  TextFormField(
                    style: TextStyle(fontSize: 15,color: AppColors.textColor),
                    maxLines: 1,
                    textAlignVertical: TextAlignVertical.center,
                    textInputAction: TextInputAction.next,
                    keyboardType: TextInputType.text,
                    autofocus: false,
                    cursorColor: Theme.of(context).primaryColor,
                    validator: (value) {
                      return value.length == 0 ? '请输入绑定手机号' : null;
                    },
                    onChanged: (value){
                      _mobile = value;
                    },
                    onSaved: (value) {
                      _mobile = value;
                    },
                    textAlign: TextAlign.start,
                    decoration: InputDecoration(
                      suffixIcon: IconButton(
                        splashColor: Colors.transparent,
                        highlightColor: Colors.transparent,
                        constraints: BoxConstraints.loose(Size(24, 24)),
                        iconSize: 1,
                        icon: Icon(Icons.clear,color: Colors.white,),
                        onPressed: () {
                        },
                      ),
                      border: UnderlineInputBorder(
                        borderSide: BorderSide.none,
                      ),
                      errorMaxLines: 1,
                      counterText: '',
                      contentPadding: EdgeInsets.only(left: 10),
                      hintText: "请输入绑定手机号",
                      hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
                    ),
                  ),
                  Divider(
                    height: 2,
                    color: HexColor("#EAEAEA"),
                  ),
                  TextFormField(
                    style: TextStyle(color: Colors.black,fontSize: 15),
                    maxLines: 1,
                    textAlignVertical: TextAlignVertical.center,
                    textInputAction: TextInputAction.done,
                    maxLength: 4,
                    keyboardType: TextInputType.numberWithOptions(),
                    autofocus: false,
                    obscureText: false,
                    cursorColor: Theme.of(context).primaryColor,
                    validator: (value) {
                      return value.length == 4 ? null : '${message['enterCode']}';
                    },
                    onSaved: (value) {
                      _smsCode = value;
                    },
                    decoration: InputDecoration(
                      fillColor: Colors.white,
                      filled: true,
                      prefixIconConstraints: BoxConstraints.loose(Size(64, 50)),
                      suffixIconConstraints: BoxConstraints.loose(Size(100, 56)),
                      suffixIcon: CountdownView(
                        key: _countdownKey,
                        hint: Text(
                          "${message['getCode']}",
                          style: TextStyle(color: AppColors.primaryColor, fontSize: 14),
                        ),
                        onPressed: () {
                          closeKeyboard(context);
                          _onGetCode();
                        },
                      ),
                      border: UnderlineInputBorder(
                        borderSide: BorderSide.none,
                        borderRadius: const BorderRadius.all(Radius.circular(24)),
                      ),
                      errorMaxLines: 1,
                      counterText: '',
                      contentPadding: EdgeInsets.only(left: 10, right: 16),
                      hintText: "${message['enterCode']}",
                      hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
                    ),
                  ),
                  Divider(
                    height: 2,
                    color: HexColor("#EAEAEA"),
                  ),
                  TextFormField(
                    style: TextStyle(fontSize: 15,color: AppColors.textColor),
                    maxLines: 1,
                    textAlignVertical: TextAlignVertical.center,
                    textInputAction: TextInputAction.next,
                    keyboardType: TextInputType.phone,
                    autofocus: false,
                    cursorColor: Theme.of(context).primaryColor,
                    validator: (value) {
                      return value.length == 0 ? '${message['enterInvitation']}' : null;
                    },
                    onSaved: (value) {
                      _inviteCode = value;
                    },
                    textAlign: TextAlign.start,
                    decoration: InputDecoration(
                      suffixIcon: IconButton(
                        splashColor: Colors.transparent,
                        highlightColor: Colors.transparent,
                        constraints: BoxConstraints.loose(Size(24, 24)),
                        iconSize: 1,
                        icon: Icon(Icons.clear,color: Colors.white,),
                        onPressed: () {
                        },
                      ),
                      border: UnderlineInputBorder(
                        borderSide: BorderSide.none,
                      ),
                      errorMaxLines: 1,
                      counterText: '',
                      contentPadding: EdgeInsets.only(left: 10),
                      hintText: "${message['enterInvitation']}",
                      hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
                    ),
                  ),
                  Divider(
                    height: 2,
                    color: HexColor("#EAEAEA"),
                  ),


                  SizedBox(height: 20,),
                  Padding(padding: EdgeInsets.only(left: 10,right: 10),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        GestureDetector(
                          child: Icon(
                            _isAgree ? Icons.check_circle : Icons.panorama_fish_eye,
                            size: 19,
                            color: _isAgree
                                ? AppColors.primaryColor
                                : AppColors.textHintColor,
                          ),
                          onTap: (){
                            setState(() {
                              _isAgree = !_isAgree;
                            });
                          },
                        ),
                        SizedBox(width: 1,),
                        Expanded(child: Text.rich(
                          TextSpan(
                            children: [
                              TextSpan(
                                text: "${message['loginLable']}",
                                style: TextStyle(color: AppColors.textHintColor, fontSize: 13),
                              ),
                              TextSpan(
                                text: "《${message['userAgreement']}》",
                                style: TextStyle(color: AppColors.textColor, fontSize: 13,fontWeight: FontWeight.bold),
                                recognizer: _userProtocolRecognizer,
                              ),
                              TextSpan(
                                text: "《${message['privacyAgreement']}》",
                                style: TextStyle(color: AppColors.textColor, fontSize: 13,fontWeight: FontWeight.bold),
                                recognizer: _privacyProtocolRecognizer,
                              ),
                            ],
                          ),
                          maxLines: 2,
                        ),
                        )
                      ],
                    ),
                  ),
                  SizedBox(height: 30,),
                  SizedBox(
                    width: double.infinity,
                    height: 42,
                    child: ElevatedButton(
                      child: Text("${message['register']}"),
                      style: ButtonStyle(
                        backgroundColor: MaterialStateProperty.all(AppColors.primaryColor),
                        shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(8))),//圆角弧度
                      ),
                      onPressed: _onRegister,
                    ),
                  ),


                  SizedBox(height: 40,),

                  // Column(
                  //   mainAxisSize: MainAxisSize.min,
                  //   children: [
                  //     Text("苹果系统或者网页版",style: TextStyle(color: AppColors.textHintColor),),
                  //     Text("Apple system or web version",style: TextStyle(color: AppColors.textHintColor),),
                  //     SizedBox(height: 8,),
                  //     Row(
                  //       mainAxisSize: MainAxisSize.min,
                  //       children: [
                  //         Text("http://app.999nineclub.com",style: TextStyle(color: AppColors.primaryColor),),
                  //         SizedBox(width: 20,),
                  //         Text("${message['share3']}",style: TextStyle(color: AppColors.primaryColor),).addGesture(() {
                  //           ClipboardData d = new ClipboardData(text: "http://app.999nineclub.com");
                  //           Clipboard.setData(d);
                  //           ToastUtils.show("${message['share4']}", context);
                  //         })
                  //       ],
                  //     )
                  //
                  //   ],
                  // )

                ],
              ),
            )
        ),
      )
    );
  }
  void _onGetCode(){
    if(_mobile == null){
      ToastUtils.show("请输入绑定手机号", context);
      return;
    }
    _countdownKey.currentState.state = CountdownState.loading;
    LoadingApi.func(AuthRepository().getSmsCode(2,phone: _mobile), context,showLoading: false,complete: (value){
      _countdownKey.currentState.state = CountdownState.countdown;
      ToastUtils.show("${message['sendSuccess']}", context);
    },error: (error){
      _countdownKey.currentState.state = CountdownState.init;
      ToastUtils.show("$error", context);
    });
  }
  void _onRegister(){
    var _state = _formKey.currentState;
    _state.save();
    if (!_state.validate()) {
      return;
    }
    if (!_isAgree) {
      ToastUtils.show("${message['qxtyxy']}", context);
      return;
    }
    if(_pwd1 != _pwd2){
      ToastUtils.show("${message['pwdInconformity']}", context);
      return;
    }
    closeKeyboard(context);
    LoadingApi.func(AuthRepository().register(_account, _pwd2, _smsCode, _inviteCode,_mobile), context,complete: (v){
      ToastUtils.show("${message['regSuccess']}", context);
      Navigator.of(context).pop();
    },error: (e){
      ToastUtils.show("$e", context);
    });
  }
}